#include "dialog.h"
#include "ui_dialog.h"

Dialog::Dialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::Dialog)
{
    ui->setupUi(this);
    ui->lineEditId->setText("192.168.");
    ui->spinBox->setValue(8887);    // 默认端口8887

    // 连接按钮点击事件
    connect(ui->pushButtonConnect,SIGNAL(clicked()),
            this,SLOT(btnConnectClickedSlot()));
    // 发送按钮点击事件
    connect(ui->pushButtonSend,SIGNAL(clicked()),
            this,SLOT(btnSendClickedSlot()));
    socket = new QTcpSocket(this);

    //查询按钮点击事件
    connect(ui->pushButtonHistory,SIGNAL(clicked()),
            this,SLOT(queryHistorySlot()));

    // 连接信号槽
    connect(socket,SIGNAL(connected()),
            this,SLOT(connectedSlot()));
    connect(socket,SIGNAL(disconnected()),
            this,SLOT(disconnectedSlot()));
    // 读取服务器发送的消息
    connect(socket, SIGNAL(readyRead()),
            this, SLOT(readMessage()));

}

Dialog::~Dialog()
{
    if(socket->isOpen())
    {
        socket->close();  // 关闭连接
    }
    delete ui;
}

//链接槽函数
void Dialog::btnConnectClickedSlot()
{
    if(ui->pushButtonConnect->text() == "连接")
    {
        QString ip = ui->lineEditId->text();    // 获取IP地址
        int port = ui->spinBox->value();         // 获取端口
        socket->connectToHost(ip,port);           // 尝试连接到指定的服务器和端口
    }
    else if(ui->pushButtonConnect->text() == "断开连接")
    {
        socket->disconnectFromHost();            // 断开与服务器的连接
    }

}

//发送消息槽函数
void Dialog::btnSendClickedSlot()
{
    QString text = ui->lineEditSend->text();  // 获取用户输入的消息
    if(text.isEmpty())
    {
        QMessageBox::warning(this,"提示","请输入要发送的内容");
        return ;
    }
    // 获取当前时间戳
    QString timeStamp = QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss");

    // 显示带时间戳的消息
    timeStamp.append("\n").append(text);
    ui->textBrowser->append(timeStamp);
    QByteArray buffer = text.toUtf8();    // 将文本转换为UTF-8字节流

    socket->write(buffer);// 发送消息到服务器
    ui->lineEditSend->clear();  // 清空输入框
}


void Dialog::connectedSlot()
{
    ui->pushButtonConnect->setText("断开连接");   // 改变按钮为"断开连接"
    ui->pushButtonSend->setEnabled(true);              // 启用发送按钮
}


void Dialog::disconnectedSlot()
{
    ui->pushButtonConnect->setText("连接");          // 改变按钮为"连接"
    ui->pushButtonSend->setEnabled(false);            // 禁用发送按钮
}

//读取消息
void Dialog::readMessage()
{
    QByteArray buffer = socket->readAll();            // 读取服务器发来的消息
    QString message = QString::fromUtf8(buffer);  // 将字节流转换为字符串
    // 在聊天框中显示服务器的消息
    ui->textBrowser->append(message);
}

//查询聊天记录的槽函数
void Dialog::queryHistorySlot()
{
    QString text = "history";
    QByteArray buffer = text.toUtf8();    // 将文本转换为UTF-8字节流
    socket->write(buffer);// 发送消息到服务器
    ui->textBrowser->clear();
}
